package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.error.BusinessException;
import org.example.error.EmBusinessError;
import org.example.response.CommonReturnType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

public class BaseController {
    // 1. 初始化SLF4J日志（关键：打印异常堆栈）
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
    //定义exceptionhandler解决未被controller层吸收的exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex) {
        Map<String, Object> responseData = new HashMap<>();
        if(ex instanceof BusinessException){ //判断ex是否是BusinessException类（或接口）的实例
            BusinessException businessException = (BusinessException) ex;
            logger.error("业务异常：errCode={}, errMsg={}", businessException.getErrcode(), businessException.getErrMsg());
            responseData.put("errCode", businessException.getErrcode());
            responseData.put("errMsg", businessException.getErrMsg());
        }else{ //JVM抛出的异常，或是其他未被controller层吸收的异常
            logger.error("未知异常：请求路径={}", request.getRequestURI(), ex);
            responseData.put("errCode", EmBusinessError.UNKNOW_ERROR.getErrcode());
            responseData.put("errMsg", EmBusinessError.UNKNOW_ERROR.getErrMsg());
        }
        return CommonReturnType.create(responseData, "fail");

    }
}
